package org.chen.spring.core.factory;

import org.chen.spring.core.annotation.Component;
import org.chen.spring.core.annotation.Import;
import org.chen.spring.core.annotation.Scope;
import org.chen.spring.core.annotation.Service;

import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.util.List;

/**
 * @author Chen
 * @since 2023/6/7 20:57
 */
public class BeanScanBean extends ScanBean{

    public BeanScanBean(String componentScan) {
        super(componentScan);
    }

    @Override
    protected void assembleBeanDefinition(Class<?> bean, Annotation annotation) {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType == Import.class || annotationType.isAnnotationPresent(Import.class)) {
            Class<?>[] value;
            if (annotationType == Import.class) {
                value = ((Import) annotation).value();
            } else {
                value = annotationType.getAnnotation(Import.class).value();
            }
            for (Class<?> aClass : value) {
                //如果是个接口
                if (aClass.isInterface()) {
                    //获取所有实现类
                    List<Class<?>> allInterfaceAchieveClass = getAllInterfaceAchieveClass(aClass);
                    for (Class<?> interfaceAchieveClass : allInterfaceAchieveClass) {
                        addBeanDefinition(interfaceAchieveClass);
                    }
                } else {
                    addBeanDefinition(aClass);
                }
            }
        }
        if (annotationType == Component.class || annotationType.isAnnotationPresent(Component.class)) {
            String beanName = bean.getSimpleName();
            //Server处理
            if (annotationType == Service.class) {
                beanName = bean.getAnnotation(Service.class).value();
                if ("".equals(beanName)) {
                    Class<?>[] interfaces = bean.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        beanName = anInterface.getSimpleName();
                    }
                }
                //Controller 处理
            }
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setType(bean);
            beanDefinition.setScope("singleton");
            if (bean.isAnnotationPresent(Scope.class)) {
                beanDefinition.setScope(bean.getAnnotation(Scope.class).value());
            }
            beanDefinitionMap.put(Introspector.decapitalize(beanName), beanDefinition);
        }
    }
}
